package com.ning.parking.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ning.parking.config.CmdTypeEnum;
import com.ning.parking.config.GlobalVariableUtils;
import com.ning.parking.config.WebSocketServer;
import com.ning.parking.domain.dto.Message;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.util.Date;

/**
 * 发布消息
 */
@Slf4j
public class PublishRoute {

    static WebSocketServer webSocketServer;

    static {
        webSocketServer = SpringUtil.getBean(WebSocketServer.class);
    }

    /**
     * 向岗亭端输出即时数据
     *
     * @param body    is 传输客户端消息体
     * @param cmdType is 指令
     */
    public static void pushBroadcast(CmdTypeEnum cmdType, Long from,Object body) {



        if (body == null ||cmdType == null) {
            log.info("message_cmd_指令不能为空:{}", cmdType);
            return;
        }

        pushMsg(Message.builder()
                .cmdType(cmdType)
                .body(body)
                .to(String.valueOf(from))
                .from(String.valueOf(from))
                .build());
        log.info("{}发送岗亭数据-->{}",cmdType,JSONObject.toJSON(body));
    }


    /**
     * 向客户端推送消息
     *
     * @param message is 消息体
     * @return the 是否成功
     */
    public static boolean pushMsg(Message message) {
        webSocketServer.sendInfo(message.getTo(), getMessageStr(message));
        return true;
    }
    public static void onClose(Session session, String userId) {
        webSocketServer.onClose(session,userId);
    }

    /**
     * 将实体转换成字符串
     *
     * @param massage is 发送消息体
     * @return
     */
    private static String getMessageStr(Message massage) {
        return JSON.toJSONString(massage);
    }


}
